#ifndef TEXTURE_H
#define TEXTURE_H

/* Create texture */
unsigned int create_texture(const char *file_name);

#endif /* END TEXTURE_H */

#ifdef TEXTURE_IMPLEMENTATION

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

unsigned int create_texture(const char *file_name)
{
    unsigned int texture_id;
    glGenTextures(1, &texture_id);
    glBindTexture(GL_TEXTURE_2D, texture_id);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);   
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    stbi_set_flip_vertically_on_load(GL_TRUE);
    int width, height, nrChannels;
    unsigned char *data = stbi_load(file_name, &width, &height, &nrChannels, 0);
    if (data)
    {
        int channels = 0;
        switch (nrChannels)
        {
        case 3:
            channels = GL_RGB;
            break;
        case 4:
            channels = GL_RGBA;
        default:
            break;
        }
        glTexImage2D(GL_TEXTURE_2D, 0, channels, width, height, 0, channels, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        fprintf(stderr, "texture id:%u Failed to load texture\n", texture_id);
    }
    stbi_image_free(data);
    return texture_id;
}

#endif